package quotation.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;


@Configuration
public class OncePerRequest extends OncePerRequestFilter {

    private static final Logger log = LoggerFactory.getLogger(OncePerRequest.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        log.info("当前请求URL:{},当前请求URI:{},请求IP:{},当前sessoinID：{}",
                request.getRequestURL(), request.getRequestURI(), request.getRemoteHost(), request.getSession().getId());
        /** 打印请求头信息 */
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            log.info("当前请求header信息---{}:{}", name, request.getHeader(name));
        }

        // 防止流读取一次后就没有了, 所以需要将流继续写出去，提供后续使用
//        ServletRequest requestWrapper = new BodyReaderWrapper(request);
        /** 打印请求参数信息 */
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement();
            log.info("当前请求参数param---{}:{}", name, request.getParameter(name));
        }
        filterChain.doFilter(request, response);
    }


}
